package com.nakamachizu.controller;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.base.LoginBaseController;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.model.MapData;
import com.nakamachizu.service.MapDataService;

public class MakeController extends LoginBaseController {

    @Override
    protected Navigation execute() throws Exception{
        
        
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if(user == null){
            return redirect(userService.createLoginURL(request.getRequestURI()));
            //response.sendRedirect(userService.createLoginURL(request.getRequestURI()));

        }else{
            String logoutUrl = userService.createLogoutURL("/");
            requestScope("logoutUrl", logoutUrl);
            requestScope("email", user.getEmail());
            requestScope("nickName", user.getNickname());
        }
        
        MapDataService service = new MapDataService();
        MapData map = service.getMapData(user.getEmail());
        
        if(map != null){
            service.deleteMapData(map);
        }

        map = new MapData();
        map.setAdminMailAddress(user.getEmail());
        map.setExpire(service.getExpire(AppConstant.DEFAULT_EXPIRE_DAYS()));
        map.setFromMailAddress(AppConstant.FROM_MAIL_ADDRESS_USER());
        map.setLineType(AppConstant.LINE_TYPE_LINE());
        map.setAccessLevel(AppConstant.ACCESSLEVEL_ALL());
        map.setAccessKey(service.makeAccessKey());
        Datastore.put(map);
 
        return redirect("/view");
    }
    

}
